package com.example.multithread.no1115;

import java.util.concurrent.Semaphore;

public class SemaphoreFooBar {

    private int n;

    public SemaphoreFooBar(int n) {
        this.n = n;
    }
    Semaphore foo = new Semaphore(1);
    Semaphore bar = new Semaphore(0);


    public static void main(String[] args) {
        SemaphoreFooBar fooBar = new SemaphoreFooBar(2);
        new Thread(() -> {
            try {
                fooBar.foo();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                fooBar.bar();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void foo() throws InterruptedException {

        for (int i = 0; i < n; i++) {
            foo.acquire();
            System.out.print("foo");
            bar.release();
        }
    }

    public void bar() throws InterruptedException {

        for (int i = 0; i < n; i++) {
            bar.acquire();
            System.out.print("bar");
            foo.release();
        }
    }
}
